import {
  login,
  getInfo,
  get,
  getAll,
  deleteById,
  create,
  update,
  getRoles,
  changeLanguage
} from '@/api/user'
import { getToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'
import appconst from '@/vendor/abp/appconst'

const state = {
  token: getToken(),
  name: '',
  avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',

  loading: false, // 控制非dialog界面的loading
  list: [],
  totalCount: 0,
  pageSize: 10,
  currentPage: 1,
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },

  SET_PAGE_SIZE(state, size) {
    state.pageSize = size
  },
  SET_CURRENT_PAGE(state, page) {
    state.currentPage = page
  }
}

const actions = {
  // user login
  login({ commit }, payload) {
    return new Promise((resolve, reject) => {
      login(payload.data)
        .then(rep => {
          const { data } = rep

          var tokenExpireDate = payload.data.rememberMe
            ? new Date(
              new Date().getTime() + 1000 * data.result.expireInSeconds
            )
            : undefined

          abp.auth.setToken(data.result.accessToken, tokenExpireDate)
          abp.utils.setCookieValue(
            appconst.authorization.encrptedAuthTokenName,
            data.result.encryptedAccessToken,
            tokenExpireDate,
            abp.appPath
          )

          // commit('SET_TOKEN', data.result.accessToken)
          // setToken(data.token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response

          if (!data) {
            reject('Verification failed, please Login again.')
          }

          const { name, avatar } = data

          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise(resolve => {
      removeToken()
      location.reload()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      // commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  get({ state }, payload) {
    return new Promise((resolve, reject) => {
      get(payload.data.id)
        .then(rep => {
          // state.currentUser = {}
          // 下面的items把对象数组展开传入，这里只传入一个
          // state.currentUser = rep.data.result
          resolve(rep.data.result)
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {
          state.loading = false
        })
    })
  },

  getAll({ state }, payload) {
    return new Promise((resolve, reject) => {
      state.loading = true
      getAll(payload.data)
        .then(response => {
          state.list = []
          state.list.push(...response.data.result.items)
          state.totalCount = response.data.result.totalCount
          resolve(response.data.result)
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {
          state.loading = false
        })
    })
  },

  delete({ state }, payload) {
    return new Promise((resolve, reject) => {
      state.loading = true
      deleteById(payload.data.id)
        .then(response => {
          resolve(response.data.result)
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {
          state.loading = false
        })
    })
  },

  create({ state }, payload) {
    return new Promise((resolve, reject) => {
      state.loading = true
      create(payload.data)
        .then(response => {
          resolve()
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {
          state.loading = false
        })
    })
  },

  update({ state }, payload) {
    return new Promise((resolve, reject) => {
      state.loading = true
      update(payload.data)
        .then(response => {
          resolve()
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {
          state.loading = false
        })
    })
  },

  getRoles({ state }) {
    return new Promise((resolve, reject) => {
      state.loading = true
      getRoles()
        .then(response => {
          state.roles = []
          state.roles.push(...response.data.result.items)
          resolve(response.data.result.items)
        })
        .catch(error => {
          reject(error)
        })
        .finally(() => {
          state.loading = false
        })
    })
  },

  async changeLanguage({ state }, payload) {
    return new Promise((resolve, reject) => {
      changeLanguage(payload.data)
        .then(() => {
          abp.utils.setCookieValue(
            'Abp.Localization.CultureName',
            payload.data.languageName,
            new Date(new Date().getTime() + 5 * 365 * 86400000),
            abp.appPath
          )
          window.location.reload()
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
